package qc.module.qms.logger;

import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import qc.common.core.constants.QmsMQConstant;
import qc.common.core.utils.QmsTimeUtil;
import qc.module.qms.dto.mq.QmsMqPointDataMessageDto;
import qc.module.qms.service.log.QmsLogPointDataService;

/**
 * QMS点号数据日志Consumer，保存、日志到数据库
 * 点号数据日志使用的消息与点号数据消息为同一个，通过不同的消费者分组进行区分
 *
 * @author QuCheng Tech
 * @since 2025/8/22
 */
@Component
@RocketMQMessageListener(
        topic = QmsMQConstant.MQ_POINTDATA_TOPIC,
        consumerGroup = QmsMQConstant.MQ_POINTDATA_CONSUMER_LOG_GROUP
)
public class QmsPointDataLogConsumer implements RocketMQListener<QmsMqPointDataMessageDto> {
    private static final Logger logger = LoggerFactory.getLogger(QmsPointDataLogConsumer.class);

    @Autowired
    private QmsLogPointDataService logPointDataService;

    @Override
    public void onMessage(QmsMqPointDataMessageDto message) {
        if (message != null) {
            try {
                logger.debug("onMessage 点号数据日志保存，点号[" + message.getPointid() + "]，时段类型[" + message.getTmseg()
                        + "]，是否为人工操作[" + message.isManual() + "]，操作用户名称[" + message.getUserName() + "]，数据质量[" + message.getQuality()
                        + "]，数据时间段[" + QmsTimeUtil.format(message.getBeginTime(), message.getTmseg()) + "]-[" + QmsTimeUtil.format(message.getEndTime(), message.getTmseg())
                        + "]，成功条数[" + message.getAffectCount() + "]，失败条数[" + message.getFailCount() + "]");
                //通过MQ进入到此点号数据日志保存消费者中的均是已经发送至MQ成功的消息
                logPointDataService.add(message, true);
            } catch (Exception ex) {
                logger.error("根据MQ中的点号数据消息进行点号数据日志保存到数据库时异常，" + ex.getMessage());
            }
        }
    }
}
